<?php namespace App\Http\Controllers\Api;

use App\Files;
use App\Http\Services\FileManager;
use App\Http\Services\Tools;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\Weibo\WeiboLogin;
use App\Http\Services\YunPian;
use App\Http\Controllers\Controller;
use App\Images;
use App\Plan;
use App\PlanJoin;
use App\User;
use App\UserInfo;
use App\VerifyPhone;
use Carbon\Carbon;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;

class AuthController extends Controller
{

    /**
     * 获取手机验证码
     *
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getVerifyCodeByPhone(Request $request){

        $phone          = $request->get('phone');
        $isAttact       = VerifyPhone::whereIp($request->ip())->orderBy('created_at', 'desc')->first();
        $isAttact_count = VerifyPhone::whereIp($request->ip())->count();

        if ($isAttact_count > 3 && $isAttact->created_at->timestamp + 60 > time())
            return response()->json(['level'=>'error','message' => '请等待60秒后再发送']);
        if ($isAttact_count > 24 && $isAttact->created_at->timestamp + 60 * 60 * 24 > time())
            return response()->json(['level'=>'error','message' => '不允许访问！']);

        $result = VerifyPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($result && 60 + $result->created_at->timestamp > time())
            return response()->json(['level'=>'error','message' => '请等待60秒后再发送']);

        VerifyPhone::wherePhone($phone)->delete();

        $VerifyCodeByPhone                 = new VerifyPhone();
        $VerifyCodeByPhone->phone          = $phone;
        $VerifyCodeByPhone->verify_code    = sprintf("%04d", rand(1000, 9999));
        $VerifyCodeByPhone->ip             = $request->ip();
        $VerifyCodeByPhone->ensure_session = '';

        $sendSms = new YunPian();
        $sendSms->sendBasicSmsWithCode($phone,$VerifyCodeByPhone->verify_code);

        $dataResult = $VerifyCodeByPhone->save();

        return response()->json(['level'=>'success','message'=>trans('验证码发送成功')]);
    }

    public function wechatLogin(Request $request){
        $state = $request->get('state');

        $state = !is_null($state) ? $state : 0;
        $callbackUrl = route('Api.Wechat.wechatCallback');
        $url         = WechatLogin::buildRedirectUrl($callbackUrl,$state);
        return redirect($url);
    }

    public function wechatCallback(Request $request){
        $code       = $request->get('code');
        $state      = $request->get('state');

        /** @var  WechatLogin $result */
        $result = WechatLogin::getWechatUserInfo($code);

        $accessToken = $result->getAccessToken();
        $openId      = $result->getOpenId();
        $nickname    = $result->getNickname();
        $sex         = $result->getSex();
        $headImgUrl  = $result->getHeadimgurl();
        $province    = $result->getProvince();
        $city        = $result->getCity();
        $unionid     = $result->getUnionid();

        /** @var  User $userModel */
        $userModel = User::whereWechatOpenid($openId)->first();

        if($userModel){
            Auth::login($userModel, 1);

        }else{
            $userModel = new User();
            $userModel->wechat_openid   = $openId;
            $userModel->password = bcrypt('123456');
            $userModel->reg_ip   = $request->ip();
            $userModel->reg_time = Carbon::now();
            $userModel->save();

            $userInfo = new UserInfo();
            $userInfo->user_id  = $userModel->id;
            $userInfo->nickname = $nickname;
            $userInfo->sex      = $sex;
            $userInfo->province = $province;
            $userInfo->city     = $city;
            $userInfo->save();

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatImg($headImgUrl,'oss');
            if($fileModel){
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if(!$imageModel){
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name= 'wechat_img';
                    $imageModel->img_type= $fileModel->file_type;
                    $imageModel->save();

                    $userInfo->photo_id = $imageModel->id;
                    $userInfo->save();
                }
            }
        }

        return redirect(route('Home.Page.index'));
    }

    public function weiboLogin(){
        $callbackUrl = 'http://wtb100.com';
        $url         = WeiboLogin::buildRedirectUrl($callbackUrl);
        return redirect($url);
    }

    public function weiboCallback(Request $request){
        $code = $request->get('code');


    }

    public function signIn(Guard $guard,Request $request){
        $phone      = $request->get('phone');
        $verifyCode = $request->get('code');

        if(is_null($phone))
            return response()->json(['level'=>'error','message'=>'手机号不能为空！']);

        /** @var VerifyPhone $verifyCodeByPhone */
        $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verifyCode)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);
        }
        $verifyCodeByPhone -> delete();

        $orderNum = "";
        if($guard->guest()){
            /** @var User $thatUser */
            $userModel = User::wherePhone($phone)->first();

            if(!$userModel){
                $userModel = new User();
                $userModel->phone    = $phone;
                $userModel->password = bcrypt('123456');
                $userModel->reg_ip   = $request->ip();
                $userModel->reg_time = Carbon::now();
                $userModel->save();

                $userInfo = new UserInfo();
                $userInfo->user_id = $userModel->id;
                $userInfo->save();
            }

            Auth::login($userModel);

            $result = self::buildOrder($userModel);
            if($result){
                $orderNum = $result;
            }
        }else{
            /** @var User $userModel */
            $userModel = $guard->user();
            if(is_null($userModel->phone)){
                $userModel->phone = $phone;
                $userModel->save();
            }

            $result = self::buildOrder($userModel);
            if($result){
                $orderNum = $result;
            }
        }

        return response()->json(['level'=>'success','message' => '登录或绑定成功','data'=>$userModel,"order_num"=>$orderNum]);
    }

    public static function buildOrder(User $user){
        $thatPlan = Plan::whereStatus(1)->first();

        $hasPlanJoin = PlanJoin::whereUserId($user->id)->wherePlanId($thatPlan->id)->whereStatus(1)->whereIsPay(1)->first();
        if($hasPlanJoin){
            return "has_join";
        }

        if(!$thatPlan)
            return false;

        $orderNum = Tools::makeBillNum();

        $planJoin            = new PlanJoin();
        $planJoin->order_num = $orderNum;
        $planJoin->plan_id   = $thatPlan->id;
        $planJoin->user_id   = $user->id;
        $planJoin->amount    = $user->phone=="15999969373"? 0.01 : $thatPlan->amount;
        $planJoin->status   = 1;
        $planJoin->save();

        return $orderNum;
    }

    public function loginOut(Guard $guard){
        $guard->logout();

        return redirect()->route('Home.Auth.login');
    }

    public function ResetPassword(Request $request){
        $phone       = $request->get('phone');
        $verify_code = $request->get('code');
        $password    = $request->get('password');

        /** @var User $user */
        $user = User::wherePhone($phone)->first();
        if(!$user)
            return response()->json(['level'=>'error','message'=>'当前账号不存在！']);

        $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verify_code)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 <time())
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);

        $verifyCodeByPhone->delete();

        $user->password = bcrypt($password);
        $user->save();
        return response()->json(['level'=>'success','message' => '重置密码成功']);
    }

    public function captcha()
    {
        //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        Session::put('milkcaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }
}